<?php

namespace app\common\model;
use think\Session;
use think\Model;

class Admin extends Model {

    protected $insert = ['create_time'];

    protected function initialize() {
        parent::initialize();
    }

    /**
     * 验证用户名密码
     * @return boolean
     */
    public function checkLogin($data) {
        $admin_password = $data['admin_password'];
        $admin_info = model('Admin')->where("admin_name='{$data['admin_name']}'")->find();
        
        if ($admin_info) {
            $admin_info = $admin_info->toArray();
            $len = strlen($admin_password);
            if ($len != 32) {
                if ($admin_info['admin_password'] == md5($admin_password)) {
                    if(!self::isBan($admin_info)){
                        die(\UtilD::handleResult(0, '你的账号已被禁用，请联系超级管理员！'));
                    }
                    self::createSession($admin_info);
                    return 2;
                }
            } else {
                if ($admin_info['admin_password'] == $admin_password) {
                    if(!self::isBan($admin_info)){
                        return 3;
                    }
                    self::createSession($admin_info);
                    return 2;
                }
            }
            return 1;
        }
        return 0;
    }
    
    /**
     * 管理员是否禁用
     * @param type $admin_info
     * @return type
     */
    protected static function isBan ($admin_info) {
       return  $admin_info['admin_status'] == 0 ? false : true;
    }

    /**
     * 登录时创建会话SESSION
     * @param type $admin_info
     * @return type
     */
    protected static function createSession($admin_info = array()) {
        if (empty($admin_info) || !is_array($admin_info))
            return;
            Session::set('admin_info', $admin_info);
        
        // 如果用户点击的保存登录状态，那么就存到cookie
        if (input('post.remember')) {
            $aMonth = time() + 30 * 24 * 3600; //保存一个月
            $des_key = config('COOKIE_ENCRYPTION');
            $admin_name = \UtilD::encrypt($admin_info['admin_name'], $des_key);
            $admin_password = \UtilD::encrypt($admin_info['admin_password'], $des_key);
            setcookie('admin_name', $admin_name, $aMonth, '/');
            setcookie('admin_password', $admin_password, $aMonth, '/');
        }
        //登录时间 ip 次数更新 
        $update_info = array(
            'login_num' => ($admin_info['login_num'] + 1),
            'login_time' => time(),
            'login_ip' => request()->ip(),
        );
        model('Admin')->save($update_info,['admin_id'=>$admin_info['admin_id']]);
    }

}
